﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<style>
    .texts-input {
        margin-top: 20px; /* 每个文本框下方留出20px的间距 */
        width: 100%;
    }
</style>
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
    <div class="search-box">
        <div class="layui-form texts-input">
            <div class="layui-form-item" style="margin-bottom: 0;">
                <label class="layui-form-label">发料单编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="issuingCode" name="issuingCode" placeholder="请输入发料单编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">外协工单编码:</label>
                <div class="layui-input-inline">
                    <input type="text" id="orderCode" name="orderCode" placeholder="请输入外协工单编码" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">供应商编码:</label>
                <div class="layui-input-inline">
                    <input type="text" id="supplierCode" name="supplierCode" placeholder="请输入供应商编码" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">发料日期:</label>
                <div class="layui-input-inline">
                    <input type="text" id="issuingDate" name="issuingDate" placeholder="请选择发料日期" autocomplete="off" class="layui-input" readonly>
                </div>
                <button class="layui-btn layui-bg-blue" lay-submit lay-filter="searchForm">
                    <i class="layui-icon layui-icon-search"></i> 搜索
                </button>
                <button type="reset" class="layui-btn layui-btn-primary" onclick="resetForm()">
                    <i class="layui-icon layui-icon-refresh"></i> 重置
                </button>
                <button type="button" class="layui-btn layui-bg-blue" onclick="openAddDialog()"><i class="layui-icon layui-icon-addition"></i>新增</button>
                <button type="button" id="batchDeleteBtn" class="layui-btn layui-bg-red layui-btn-disabled" onclick="deleteSelected()" disabled><i class="layui-icon layui-icon-delete"></i>批量删除</button>
            </div>
        </div>
    </div>
    <div class="page-container">
        @Html.AntiForgeryToken()
        <table class="layui-table" lay-size="lg">
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="selectAll" lay-skin="primary" title="全选">
                        <span id="selectAllLabel" style="margin-left: 5px; font-size: 12px; color: #666;">全选</span>
                    </th>
                    <th>发料单编号</th>
                    <th>发料单名称</th>
                    <th>外协工单编码</th>
                    <th>供应商编码</th>
                    <th>发料日期</th>
                    <th>单据状态</th>
                    <th>是否发料</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb">
            </tbody>
        </table>
        <div id="pagination"></div>
    </div>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    layui.use(['layer', 'form', 'laydate', 'laypage'], function(){
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;
        var laypage = layui.laypage;
        
        var currentPage = 1;
        var pageSize = 10;
        var total = 0;
        var selectedItems = []; // 存储选中的项目
        
        // 初始化日期选择器
        laydate.render({
            elem: '#issuingDate',
            format: 'yyyy-MM-dd'
        });
        
        // 页面加载时获取数据
        $(document).ready(function() {
            loadData();
            
            // 绑定全选复选框事件（备用方案）
            $('#selectAll').off('click').on('click', function() {
                var isChecked = $(this).prop('checked');
                $('.item-checkbox').prop('checked', isChecked);
                form.render('checkbox');
                setTimeout(function() {
                    updateSelectedItems();
                }, 100);
            });
        });
        
        // 搜索表单提交
        form.on('submit(searchForm)', function(data){
            currentPage = 1;
            loadData();
            return false;
        });
        
        // 重置表单
        window.resetForm = function() {
            $('#issuingCode').val('');
            $('#orderCode').val('');
            $('#supplierCode').val('');
            $('#issuingDate').val('');
            currentPage = 1;
            loadData();
        };
        
        // 加载数据
        function loadData() {
            var searchParams = {
                issuingCode: $('#issuingCode').val() || '',
                orderCode: $('#orderCode').val() || '',
                supplierCode: $('#supplierCode').val() || '',
                issuingDate: $('#issuingDate').val() ? new Date($('#issuingDate').val()).toISOString() : ''
            };
            
            $.ajax({
                url: '/Warehousings/GetIssuingMaterials',
                type: 'GET',
                data: searchParams,
                success: function(result) {
                    if (result && Array.isArray(result)) {
                        // 按照ID降序排序，确保最新的数据在前面，保持数据顺序稳定
                        result.sort(function(a, b) {
                            return b.id - a.id;
                        });
                        renderTable(result);
                        total = result.length;
                        renderPagination();
                    } else {
                        renderTable([]);
                        renderPagination();
                    }
                },
                error: function() {
                    layer.msg('加载数据失败', {icon: 2});
                    renderTable([]);
                }
            });
        }
        
        // 渲染表格
        function renderTable(data) {
            var tbody = $('#tb');
            tbody.empty();
            
            if (data.length === 0) {
                tbody.append('<tr><td colspan="9" style="text-align: center;">暂无数据</td></tr>');
                return;
            }
            
            // 分页处理
            var start = (currentPage - 1) * pageSize;
            var end = start + pageSize;
            var pageData = data.slice(start, end);
            
            pageData.forEach(function(item) {
                var stateText = getStateText(item.state);
                var isNoText = item.isNo === 1 ? '已发料' : '未发料';
                var issuingDate = item.issuingDate ? new Date(item.issuingDate).toLocaleDateString('zh-CN') : '';
                
                var row = '<tr data-id="' + item.id + '">' +
                    '<td><input type="checkbox" class="item-checkbox" data-id="' + item.id + '" lay-skin="primary"></td>' +
                    '<td>' + (item.issuingCode || '') + '</td>' +
                    '<td>' + (item.issuingName || '') + '</td>' +
                    '<td>' + (item.orderCode || '') + '</td>' +
                    '<td>' + (item.supplierCode || '') + '</td>' +
                    '<td>' + issuingDate + '</td>' +
                    '<td>' + stateText + '</td>' +
                    '<td>' + isNoText + '</td>' +
                    '<td>' +
                        '<button class="layui-btn layui-btn-xs" onclick="editItem(' + item.id + ')">编辑</button>' +
                        '<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteItem(' + item.id + ')">删除</button>' +
                    '</td>' +
                '</tr>';
                tbody.append(row);
            });
            
            // 重新渲染表单
            form.render('checkbox');
            
            // 绑定复选框点击事件（备用方案）
            $('.item-checkbox').off('click').on('click', function() {
                setTimeout(function() {
                    updateSelectedItems();
                }, 100);
            });
            
            // 重置全选状态和批量删除按钮
            $('#selectAll').prop('checked', false);
            $('#selectAllLabel').text('全选');
            $('#batchDeleteBtn').addClass('layui-btn-disabled').prop('disabled', true);
            selectedItems = [];
        }
        
        // 获取状态文本
        function getStateText(state) {
            switch(state) {
                case 0: return '草稿';
                case 1: return '待审核';
                case 2: return '已审核';
                case 3: return '已发料';
                default: return '未知';
            }
        }
        
        // 渲染分页
        function renderPagination() {
            if (total <= pageSize) {
                $('#pagination').empty();
                return;
            }
            
            laypage.render({
                elem: 'pagination',
                count: total,
                limit: pageSize,
                curr: currentPage,
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                jump: function(obj, first) {
                    if (!first) {
                        currentPage = obj.curr;
                        pageSize = obj.limit;
                        loadData();
                    }
                }
            });
        }
        
        // 全选/取消全选
        form.on('checkbox()', function(data) {
            if (data.elem.id === 'selectAll') {
                // 全选或全不选
                var isChecked = data.elem.checked;
                $('.item-checkbox').prop('checked', isChecked);
                form.render('checkbox');
                updateSelectedItems();
                
                // 显示选中状态
                if (isChecked) {
                    var count = $('.item-checkbox').length;
                    layer.msg('已选择 ' + count + ' 项', {icon: 1, time: 1000});
                } else {
                    layer.msg('已取消全选', {icon: 1, time: 1000});
                }
            } else if (data.elem.classList.contains('item-checkbox')) {
                updateSelectedItems();
                
                // 检查是否所有项都被选中
                var totalCheckboxes = $('.item-checkbox').length;
                var checkedCheckboxes = $('.item-checkbox:checked').length;
                var allChecked = checkedCheckboxes === totalCheckboxes;
                
                $('#selectAll').prop('checked', allChecked);
                form.render('checkbox');
                
                // 显示当前选中数量
                if (checkedCheckboxes > 0) {
                    $('#selectAllLabel').text('已选择 ' + checkedCheckboxes + ' / ' + totalCheckboxes + ' 项');
                } else {
                    $('#selectAllLabel').text('全选');
                }
            }
        });
        
        // 更新选中项目
        function updateSelectedItems() {
            selectedItems = [];
            $('.item-checkbox:checked').each(function() {
                selectedItems.push(parseInt($(this).data('id')));
            });
            
            // 更新选中数量显示
            var totalCheckboxes = $('.item-checkbox').length;
            var checkedCheckboxes = selectedItems.length;
            
            if (checkedCheckboxes > 0) {
                $('#selectAllLabel').text('已选择 ' + checkedCheckboxes + ' / ' + totalCheckboxes + ' 项');
                // 启用批量删除按钮
                $('#batchDeleteBtn').removeClass('layui-btn-disabled').prop('disabled', false);
            } else {
                $('#selectAllLabel').text('全选');
                // 禁用批量删除按钮
                $('#batchDeleteBtn').addClass('layui-btn-disabled').prop('disabled', true);
            }
        }
        
        // 打开新增弹窗
        window.openAddDialog = function() {
            layer.open({
                type: 2,
                title: '添加外协发料单',
                shadeClose: true,
                shade: 0.5,
                area: ['80%', '70%'],
                content: '/Warehousings/AddOutsourcedView',
                end: function() {
                    // 关闭弹窗后刷新数据
                    loadData();
                }
            });
        };
        
        // 打开修改弹窗
        window.openUpdateDialog = function() {
            if (selectedItems.length !== 1) {
                layer.msg('请选择一条记录进行修改', {icon: 2});
                return;
            }
            
            layer.open({
                type: 2,
                title: '修改外协发料单',
                shadeClose: true,
                shade: 0.5,
                area: ['80%', '70%'],
                content: '/Warehousings/UpdateOutsourcedView?id=' + selectedItems[0],
                end: function() {
                    // 关闭弹窗后刷新数据
                    loadData();
                }
            });
        };
        
        // 编辑单个项目
        window.editItem = function(id) {
            layer.open({
                type: 2,
                title: '修改外协发料单',
                shadeClose: true,
                shade: 0.5,
                area: ['80%', '70%'],
                content: '/Warehousings/UpdateOutsourcedView?id=' + id,
                end: function() {
                    // 关闭弹窗后刷新数据
                    loadData();
                }
            });
        };
        
        // 删除选中项目（批量删除）
        window.deleteSelected = function() {
            // 直接从DOM中获取选中的复选框
            var checkedBoxes = $('.item-checkbox:checked');
            var idsToDelete = [];
            
            checkedBoxes.each(function() {
                var id = parseInt($(this).data('id'));
                if (!isNaN(id)) {
                    idsToDelete.push(id);
                }
            });
            
            console.log('直接从DOM获取的选中项目:', idsToDelete); // 调试信息
            console.log('选中的复选框数量:', checkedBoxes.length); // 调试信息
            
            if (idsToDelete.length === 0) {
                layer.msg('请选择要删除的记录', {icon: 2});
                return;
            }
            
            // 更新selectedItems
            selectedItems = idsToDelete;
            
            layer.confirm('确定要删除选中的 ' + selectedItems.length + ' 条记录吗？', {icon: 3, title: '提示'}, function(index) {
                // 显示删除进度
                var loadingIndex = layer.load(1, {
                    shade: [0.3, '#000']
                });
                
                // 获取Token
                var token = $('input[name="__RequestVerificationToken"]').val();
                
                // 使用批量删除接口
                $.ajax({
                    url: '/Warehousings/BatchDeleteIssuingMaterials',
                    type: 'POST',
                    data: {
                        ids: selectedItems.join(','),
                        __RequestVerificationToken: token
                    },
                    success: function(result) {
                        layer.close(loadingIndex);
                        layer.close(index);
                        
                        if (result > 0) {
                            layer.msg('删除成功：共删除 ' + result + ' 条记录', {icon: 1});
                            
                            // 从当前表格中移除已删除的行
                            selectedItems.forEach(function(id) {
                                $('tr[data-id="' + id + '"]').remove();
                            });
                            
                            // 清空选中项
                            selectedItems = [];
                            $('#selectAll').prop('checked', false);
                            $('#selectAllLabel').text('全选');
                            $('#batchDeleteBtn').addClass('layui-btn-disabled').prop('disabled', true);
                            form.render('checkbox');
                            
                            // 重新计算总数和分页
                            total = total - result;
                            
                            // 如果当前页没有数据了，且不是第一页，则跳转到上一页
                            if ($('#tb tr').length === 0 && currentPage > 1) {
                                currentPage = currentPage - 1;
                                loadData();
                            } else if ($('#tb tr').length === 0) {
                                // 如果是第一页且没有数据，重新加载
                                loadData();
                            } else {
                                // 重新渲染分页
                                renderPagination();
                            }
                        } else {
                            layer.msg('删除失败：没有删除任何记录', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadingIndex);
                        layer.msg('删除失败，请重试', {icon: 2});
                    }
                });
            });
        };
        
        // 删除单个项目
        window.deleteItem = function(id) {
            layer.confirm('确定要删除这条记录吗？', {icon: 3, title: '提示'}, function(index) {
                $.ajax({
                    url: '/Warehousings/DeleteIssuingMaterials',
                    type: 'POST',
                    data: {id: id},
                    headers: {
                        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function() {
                        layer.msg('删除成功', {icon: 1});
                        layer.close(index);
                        loadData();
                    },
                    error: function() {
                        layer.msg('删除失败', {icon: 2});
                    }
                });
            });
        };
        
        // 刷新数据的全局函数，供子页面调用
        window.refreshTable = function() {
            loadData();
        };
        
        // 更新单行数据，避免整个表格重新加载
        window.updateSingleRow = function(id, updatedData) {
            var targetRow = $('tr[data-id="' + id + '"]');
            if (targetRow.length > 0) {
                // 获取状态文本
                var stateText = getStateText(updatedData.State || 0);
                var isNoText = (updatedData.IsNo === 1 || updatedData.IsNo === '1') ? '已发料' : '未发料';
                var issuingDate = '';
                
                if (updatedData.IssuingDate) {
                    var date = new Date(updatedData.IssuingDate);
                    issuingDate = date.toLocaleDateString('zh-CN');
                }
                
                // 更新表格行的内容，保持复选框和操作按钮不变
                targetRow.html(
                    '<td><input type="checkbox" class="item-checkbox" data-id="' + id + '" lay-skin="primary"></td>' +
                    '<td>' + (updatedData.IssuingCode || '') + '</td>' +
                    '<td>' + (updatedData.IssuingName || '') + '</td>' +
                    '<td>' + (updatedData.OrderCode || '') + '</td>' +
                    '<td>' + (updatedData.SupplierCode || '') + '</td>' +
                    '<td>' + issuingDate + '</td>' +
                    '<td>' + stateText + '</td>' +
                    '<td>' + isNoText + '</td>' +
                    '<td>' +
                        '<button class="layui-btn layui-btn-xs" onclick="editItem(' + id + ')">编辑</button>' +
                        '<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteItem(' + id + ')">删除</button>' +
                    '</td>'
                );
                
                // 重新渲染表单组件
                form.render('checkbox');
                
                layer.msg('数据已更新', {icon: 1, time: 1000});
            } else {
                // 如果找不到对应行，则刷新整个表格
                loadData();
            }
        };
    });
</script>
